
import Scene from "./scene";
import defined from "./core/defined";
import getElement from "./core/getElement";
import { initWebGPU } from "./util/initWebGPU";

export default class Viewer {
    resume() {
        this.paused = false;
    }
    pause() {
        this.paused = true;
    }

    container: HTMLElement;
    private options: any;
    canvas: HTMLCanvasElement;
    private scene!: Scene;
    private paused: boolean = false;

    constructor(container: string | HTMLElement, options: any) {
        if (!defined(container)) {
            throw new Error("container is required.");
        }
        this.container = getElement(container);
        this.options = options;

        this.canvas = document.createElement("canvas");
        this.canvas.className = "drengine-viewer";
        this.container.appendChild(this.canvas);
        // 禁止右键响应
        this.canvas.addEventListener("contextmenu", (event) => {
            event.preventDefault();
        });

    }

    public async init() {
        const { device, context, format, size } = await initWebGPU(this.canvas);
        this.scene = new Scene(device, context, format, size);
    }


    // start loop
    public start(cb: Function) {
        if(!this.paused){
            const now = performance.now()
            cb(now);
            this.scene.render()
        }

        requestAnimationFrame(() => this.start(cb))
    }

    // 提供公共方法访问和修改内部状态
    public getContainer(): HTMLElement {
        return this.container;
    }

    // 提供公共方法访问和修改内部状态
    public getOptions(): any {
        return this.options;
    }

    public getScene(): Scene {
        return this.scene;
    }

    public getCanvas(): HTMLCanvasElement {
        return this.canvas;
    }

}